// @ 516
// _(:з」∠)_

define([], function() {
    'use strict';

    let metror = document.querySelector(".leftMain_cont .meteorological"),
        metrorCont = metror.querySelector(".item_cont");

    RST.basic( Path + "/data/basic/meteorological.json", "", function( result ) {
        let listLi = ``,
            data = result.data;

        for ( let x = 0; x < data.length; x++ ) {
            if ( data[x].pId == "0" ) {
                let childView = loopData( data[x].id );

                listLi += `<li class="meteor_item">
                                <h class="meteor_item_head" eid="${ data[x].id }">${ data[x].text }</h>
                                <ul class="meteor_child_list">${ childView }</ul>
                            </li>`;
            }
        }

        function loopData( id ) {
            let itemView = ``;
            for ( let x = 0; x < data.length; x++ ) {
                if ( data[x].pId == id ) {
                    if ( data[x].param ) {
                        if ( data[x].detail ) {
                            itemView += `<li class="meteor_child_item">
                                                    <h class="meteor_item_head"
                                                        eid="${ data[x].id }"
                                                        pid="${ data[x].pId }"
                                                        areaCode="${ data[x].param.areaCode }"
                                                        cropValue="${ data[x].param.cropValue }"
                                                    >${ data[x].text }<span class="item_set"></span></h>
                                                </li>`;
                        } else {
                            itemView += `<li class="meteor_child_item">
                                                    <h class="meteor_item_head"
                                                        eid="${ data[x].id }"
                                                        pid="${ data[x].pId }"
                                                        areaCode="${ data[x].param.areaCode }"
                                                        cropValue="${ data[x].param.cropValue }"
                                                    >${ data[x].text }</h>
                                                </li>`;
                        }
                    } else {
                        itemView += `<li class="meteor_child_item">
                                                <h class="meteor_item_head"
                                                    eid="${ data[x].id }"
                                                    pid="${ data[x].pId }"
                                                >${ data[x].text }<span class="item_set"></span></h>
                                            </li>`;
                    }
                }
            }
            return itemView;
        }

        let metrorView = `<ul class="meteor_list">${ listLi }</ul>`;
        metrorCont.insertAdjacentHTML("beforeEnd", metrorView);

        // click event
        let item = document.querySelectorAll(".meteor_list .meteor_item_head");
        for ( let x = 0; x < item.length; x++ ) {
            item[x].addEventListener("click", function(e) {
                if ( e.target.nodeName == "H" ) {

                    // 移除所有高级选择
                    let meteorEvent = metrorCont.querySelectorAll(".item_set");
                    document.querySelector(".meteorEvent_setting").hide();
                    removeAllClass( "select", meteorEvent );

                    if ( item[x].parentNode.hasClass("select") ) {
                        item[x].parentNode.removeClass("select");
                        if ( item[x].nextElementSibling ) {
                            item[x].nextElementSibling.removeClass("select");
                        }
                        removeAllCommon();
                        MC.mapEvent.closeAllLayer();
                    } else {
                        let childItem = document.querySelectorAll(".meteor_list .meteor_child_item");
                        removeAllClass( "select", childItem );
                        
                        if ( item[x].parentNode.hasClass("meteor_child_item") ) {
                            let disBox = document.querySelector(".disaster_box"),
                                disEvent = disBox.querySelector(".item_child_list .li_item.select");
                            if ( disEvent ) disEvent.click();

                            if ( item[x].getAttribute("pid") == "900" ) {
                                singleEvent( item[x] );
                            } else {
                                resetSetting( data, item[x] );
                            }
                        } else {
                            let siblingItem = document.querySelectorAll(".meteor_list .meteor_item"),
                                siblingNextElmt = document.querySelectorAll(".meteor_list .meteor_child_list");
                            removeAllClass( "select", siblingItem );
                            removeAllClass( "select", siblingNextElmt );

                            if ( item[x].nextElementSibling ) {
                                item[x].nextElementSibling.addClass("select");
                            }
                        }

                        item[x].parentNode.addClass("select");
                    }
                }

                e.stopPropagation();
            }, false);
        }

        meteorEventClick( metrorCont );
    });

    // 点击事件
    function meteorEventClick( metrorCont ) {
        let meteorEvent = metrorCont.querySelectorAll(".item_set"),
            meteorSetting = document.querySelector(".meteorEvent_setting");
        for ( let x = 0; x < meteorEvent.length; x++ ) {
            meteorEvent[x].addEventListener( 'click', function(e) {
                if ( e.target.nodeName == "SPAN" && meteorEvent[x].parentNode.parentNode.hasClass("select") ) {
                    if ( meteorEvent[x].hasClass("select") ) {
                        removeAllClass( "select", meteorEvent );
                        meteorSetting.hide();
                    } else {
                        meteorEvent[x].addClass("select");
                        meteorSetting.show();

                        let clientY = e.clientY, offsetY = e.offsetY,
                            centerY = e.clientY - e.offsetY + 14 - 50 - ( meteorSetting.clientHeight * 0.15 );
                        meteorSetting.style.top = centerY +"px";
                    }
                }
                
                e.stopPropagation();
            }, false);
        }

    }

    // 重置高级设置
    function resetSetting( data, itemElmt ) {
        let meteorSetView = ``,
            meteorSetting = document.querySelector(".meteorEvent_setting");

        for ( let x = 0; x < data.length; x++ ) {
            if ( data[x].id == itemElmt.getAttribute("eid") ) {
                if ( data[x].detail ) {
                    for ( let y = 0; y < data[x].detail.length; y++ ) {
                        let setView = ``,
                            cData = data[x].detail[y];

                        if ( cData.detail ) {
                            let detlView = ``;

                            for ( let z = 0; z < cData.detail.length; z++ ) {
                                let select = "",
                                    detl = cData.detail[z];

                                if ( detl.select === 1 ) select = "select";
                                detlView += `<li class="${ select }" value="${ detl.value }"> ${ detl.name } </li>`;
                            }
                            setView += `<h> ${ cData.name } </h>
                                        <ul> ${ detlView } </ul>`;

                        } else if ( cData.value == "opacity" ) {
                            setView += `<h> ${ cData.name } </h>
                                        <input type="range" name="opacity" min="0" max="100" value="${ cData.default }" />`;
                        }

                        meteorSetView += `<li class="meteorSetItem ${ cData.value }"> ${ setView } </li>`;
                    }
                }
                break;
            }
        }

        meteorSetting.textContent = "";
        meteorSetting.insertAdjacentHTML("beforeEnd", meteorSetView);
        setEventClcik( data, meteorSetting );
    }

    // 高级设置事件
    function setEventClcik( data, meteorSetting ) {
        let intx = 24 * 60 * 60 * 1000,
            dataType = meteorSetting.querySelector(".dataType"),
            timeType = meteorSetting.querySelector(".timeType"),
            elmtIndex = meteorSetting.querySelector(".elmtIndex"),
            renderType = meteorSetting.querySelector(".renderType"),
            opacity = meteorSetting.querySelector("input[name='opacity']");

        // 数据类型
        if ( dataType ) {
            dataType.addEventListener("click", function(e) {
                if ( e.target.nodeName == "LI" ) {
                    e.target.removeAllClass("select");
                    e.target.addClass("select");
    
                    if ( e.target.getAttribute("value") == "observe" ) {
                        TimeLine.validMain.init({ type: "month" });
    
                        let date = Number( new Date().getDate()-1 );
                        timeLineClick({ index: date-1, status: true });
                    } else {
                        TimeLine.validMain.init({
                            type: "custom",
                            startTime: formatTime( "", "day" ),
                            endTime: formatTime( "", "day", 3 * intx )
                        });
            
                        timeLineClick({ index: 0, status: true });
                    }
                }
            }, false);
        }

        // 时间类型
        if ( timeType ) {
            timeType.addEventListener("click", function(e) {
                if ( e.target.nodeName == "LI" ) {
                    e.target.removeAllClass("select");
                    e.target.addClass("select");
    
                    let _hour = Number( new Date().getHours() ),
                        _date = Number( new Date().getDate() ),
                        _month = Number( new Date().getMonth()+1 ),
                        type = e.target.getAttribute("value");
                    
                    TimeLine.validMain.init({ type: type });
    
                    switch( type ) {
                        case "date":
                            timeLineClick({ index: _hour-2, status: true });
                        break;
                        case "month":
                            timeLineClick({ index: _date-2, status: true });
                        break;
                        case "year":
                            timeLineClick({ index: _month-2, status: true });
                        break;
                    }
                }
            }, false);
        }

        // 要素指标
        if ( elmtIndex ) {
            elmtIndex.addEventListener( 'click', function(e) {
                if ( e.target.nodeName == "LI" ) {
                    e.target.removeAllClass("select");
                    e.target.addClass("select");
    
                    let index = document.querySelector(".timeLine .line_item.select");
                    timeLineClick({ index: Number( index.getAttribute("index") ), status: false });
                }
            }, false);
        }

        // 渲染方式
        if ( renderType ) {
            renderType.addEventListener( 'click', function(e) {
                if ( e.target.nodeName == "LI" ) {
                    e.target.removeAllClass("select");
                    e.target.addClass("select");
    
                    let index = document.querySelector(".timeLine .line_item.select");
                    timeLineClick({ index: Number( index.getAttribute("index") ), status: false });
                }
            }, false);
        }

        // 透明度
        opacity.addEventListener( 'change', function(e) {
            let value = Number( e.target.value ),
                layer = MC.mapLayer.chromaticLayer;
            if ( layer ) {
                layer.setStyle({fillOpacity: value / 100 });
            }
        }, false);

        if ( meteorSetting.querySelectorAll(".select")[1] ) {
            meteorSetting.querySelectorAll(".select")[1].click();
        } else {
            Popup.tipPopup({
                type: "toast",
                content: `当前无数据！`
            });
        }
    }

    // 时间轴时间
    function timeLineClick( param ) {
        let lineBox = document.querySelector(".timeLine .line_list"),
            lineItem = lineBox.querySelectorAll(".line_item");

        if ( param.status ) {
            lineBox.addEventListener( "click", function(e) {
                if ( e.target.nodeName === "LI" || e.target.parentNode.nodeName === "LI" ) {
                    let thisItem = null,
                        thisIndex = 0;

                    if ( e.target.nodeName === "LI" ) {
                        thisItem = e.target;
                        thisIndex = thisItem.getAttribute("index");
                    }
                    if ( e.target.parentNode.nodeName === "LI" ) {
                        thisItem = e.target.parentNode;
                        thisIndex = thisItem.getAttribute("index");
                    }

                    MC.mapEvent.closeAllLayer();
                
                    // 移除右侧弹窗
                    let rightMain = document.querySelector(".rightMain");
                    if ( rightMain ) rightMain.remove();
    
                    // 移除图例
                    let legend = document.querySelector(".legend");
                    if ( legend ) legend.remove();
    
                    let meteorSet = document.querySelector(".meteorEvent_setting"),
                        dataType = meteorSet.querySelector(".dataType li.select"),
                        elmtIndex = meteorSet.querySelector(".elmtIndex li.select"),
                        renderType = meteorSet.querySelector(".renderType li.select"),
                        opacity = meteorSet.querySelector("input[name='opacity']");
    
                    let observeArea = "HHH",
                        dataValue = dataType.getAttribute("value"),
                        elementValue = ( elmtIndex ) ? elmtIndex.getAttribute("value") : "",
                        fileType = ( renderType ) ? renderType.getAttribute("value") : "",
                        observeDate = thisItem.getAttribute("time"),
                        observeHour = 24,
                        opacityValue = Number( opacity.getAttribute("value") );
                    
                    MC.mapEvent.closeEventAndLayer();

                    // 渲染方式 - render type
                    if ( dataValue == "observe" ) {
                        if ( fileType == "contour_png" ) {
                            RST.Image( "/weather/getObserveGridData?"
                                +"observeArea="+ observeArea +"&elementValue="+ elementValue
                                +"&fileType="+ fileType +"&fileLevel=0"
                                +"&observeDate="+ observeDate +"&observeHour="+ observeHour, "",
                            function( result ) {
                                MC.mapEvent.drawImageLayer( result.data, { opacity: opacityValue } );
                            });
                        } else if ( fileType == "json" ) {
                            RST.chromatic( "/weather/getObserveGridData?"
                                +"observeArea="+ observeArea +"&elementValue="+ elementValue
                                +"&fileType="+ fileType +"&fileLevel=0"
                                +"&observeDate="+ observeDate +"&observeHour="+ observeHour, "",
                            function( result ) {
                                MC.mapEvent.drawChromatic( result.data, { opacity: opacityValue } );

                                RST.Image( "/weather/getObserveGridData?"
                                    +"observeArea="+ observeArea +"&elementValue="+ elementValue
                                    +"&fileType=contour_png&fileLevel=0"
                                    +"&observeDate="+ observeDate +"&observeHour="+ observeHour, "",
                                function( resultx ) {
                                    let thisData = resultx.data,
                                        vtJson = result.data.detail.replace(/<\/?.+?>/g,"").replace(/[\r\n]/g, ""),
                                        data = JSON.parse( vtJson );
                                        
                                    thisData["productMaintitle"] = data[0].Metadata.MainTitle;
                                    thisData["productSubtitle"] = data[0].Metadata.SubTitle;
                                    
                                    MC.mapEvent.drawImageLayer( thisData, { opacity: opacityValue } );
                                });
                            });
                        }
                    } else if ( dataValue == "forecast" ) {
                        if ( fileType == "contour_png" ) {
                            RST.Image( "/weather/getForecastGridData?"
                                +"forecastArea="+ observeArea +"&elementValue="+ elementValue
                                +"&fileType="+ fileType +"&fileLevel=0&forecastLevel=0"
                                +"&forecastDate="+ observeDate, "",
                            function( result ) {
                                MC.mapEvent.drawImageLayer( result.data[ Number(thisIndex) ], { opacity: opacityValue } );
                            });
                        } else if ( fileType == "json" ) {
                            RST.chromatic( "/weather/getForecastGridData?"
                                +"forecastArea="+ observeArea +"&elementValue="+ elementValue
                                +"&fileType="+ fileType +"&fileLevel=0&forecastLevel=0"
                                +"&forecastDate="+ observeDate, "",
                            function( result ) {
                                if ( result.data[ Number(thisIndex) ] ) {
                                    MC.mapEvent.drawChromatic( result.data[ Number(thisIndex) ], { opacity: opacityValue } );
                                } else {
                                    Popup.tipPopup({ type: "toast", content: "当前无数据" });
                                }
                                
                                RST.Image( "/weather/getForecastGridData?"
                                    +"forecastArea="+ observeArea +"&elementValue="+ elementValue
                                    +"&fileType=contour_png&fileLevel=0&forecastLevel=0"
                                    +"&forecastDate="+ observeDate, "",
                                function( resultx ) {
                                    let thisData = resultx.data[ Number(thisIndex) ],
                                        vtJson = result.data[ Number(thisIndex) ].detail.replace(/<\/?.+?>/g,"").replace(/[\r\n]/g, ""),
                                        data = JSON.parse( vtJson );
                                    thisData["productMaintitle"] = data[0].Metadata.MainTitle;
                                    thisData["productSubtitle"] = data[0].Metadata.SubTitle;

                                    MC.mapEvent.drawImageLayer( thisData, { opacity: opacityValue } );
                                });
                            });
                        }
                    }
                }

                e.stopPropagation();
            }, false);
        }

        lineItem[ param.index ].click();
    }

    // 单例事件
    function singleEvent( elmt ) {
        MC.mapEvent.closeEventAndLayer();

        if ( elmt.getAttribute("eid") === "901" ) {
            RST.chromatic( "/crop/getCropDistribution?"
                +"cropArea="+ elmt.getAttribute("areaCode") +"&cropName="+ elmt.getAttribute("cropValue")
                +"&fileType=json&fileLevel=0", "",
            function( result ) {
                if ( result.data.detail ) {
                    let vtJson = result.data.detail.replace(/<\/?.+?>/g,"").replace(/[\r\n]/g, ""),
                        data = JSON.parse( vtJson );
                    gridHeatMap.initGrid( data[0], "cropDistribution" );
                }
            });
        }
    }

    // 移除所有通用
    function removeAllCommon() {
        // 隐藏高级设置
        let meteorEvent = document.querySelector(".meteor_list .meteor_child_item .item_set.select");
        if ( meteorEvent ) meteorEvent.click();

        // 移除右侧弹窗
        let rightMain = document.querySelector(".rightMain");
        if ( rightMain ) rightMain.remove();

        // 移除时间轴
        let timeLine = document.querySelector(".timeLine");
        if ( timeLine ) timeLine.remove();

        // 移除图例
        let legend = document.querySelector(".legend");
        if ( legend ) legend.remove();

        // 移除标题
        let title = document.querySelector(".title");
        if ( title ) title.remove();
    }
});